<template>
  <div class="follow">
    <div class="follow_item" v-for="item, index in followVideoData" :key="item.Video.videoId" ref="videoItems">
      <div class="follow_item_top">
        <img class="follow_item_top__avatar" @click="handleUserClick(item.Video.userId)" :src="item.Video.userAvatar"
          alt="">
        <span class="follow_item_top__username">{{ item.Video.userNickname }}</span>
      </div>
      <div class="follow_item_desc">{{ item.Video.videoDesc }}</div>
      <div class="follow_item_video">
        <!-- 视频占位符 -->
        <div v-if="!isVisible[index]" class="video_placeholder">
          <div class="video_placeholder__loading">
            <div class="loading_spinner"></div>
            <span>视频预览</span>
          </div>
        </div>
        <!-- 视频组件 -->
        <CustomVideo v-else :showProgress="false" :src="item.Video.videoPath" :active="isVisible[index]"
          @load-error="handleVideoLoadError(index)">
        </CustomVideo>
      </div>
      <div class="follow_item_bar">
        <div class="follow_item_bar_item" @click="handleLike(item.Video.videoId)">
          <Icon name="xin-2" :color="item.WSLCNum.likeNum > 0 ? 'red' : '#ccc'" size="20" />
          <span>{{ item.WSLCNum.likeNum }}</span>
        </div>
        <div class="follow_item_bar_item" @click="handleComment(item.Video.videoId, index)">
          <Icon name="pinglun" color="#fff" size="18" />
          <span>{{ item.WSLCNum.commentNum }}</span>
        </div>
        <div class="follow_item_bar_item">
          <Icon name="a-fenxiangweifenxiang" size="17" color="#fff" />
          <span>{{ item.WSLCNum.shareNum }}</span>
        </div>
      </div>
      <div class="follow_item_time">{{ formatTime(item.Video.createdAt).formatted }}</div>
    </div>
    <div class="no_data" v-if="followVideoData.length === 0">暂无关注视频</div>
    <Commentcomponent v-model="isShowComment" :commentList="commentList" @newComment="handleNewComment"
      :videoId="currentVideoId" />
    <!-- 从左到右过渡出现 用户详情页 -->
    <!-- <transition name="fade-in-right">
      <FriendsProfilePage v-if="isShowUserProfilePage" v-model="isShowUserProfilePage" :friendId="userProfileId">
      </FriendsProfilePage>
    </transition> -->
  </div>
</template>

<script setup>
import Icon from '@/components/Common/Icon/index.vue'
import CustomVideo from '@/components/Common/CustomVideo/index.vue'
import { useUserIDStore } from '@/stores/UserID';
const userIDStore = useUserIDStore();

const userId = userIDStore.userInfo?.userId
import { onMounted, ref, nextTick, watch } from 'vue';
// 导入时间格式化函数
import { useDateFormat } from '@/composables/useDateFormat'
// ✅ 创建一个工具函数：返回格式化对象 { formatted }
const formatTime = (timestamp) => {
  return useDateFormat(timestamp, 'YYYY-MM-DD', { relative: true })
}
// 关注页 视频请求
import { getFollowVideoAPI } from '@/api/follow';

// 获取关注页视频数据

const followVideoData = ref([]);
const videoItems = ref([]); // 存储视频项的DOM引用
const isVisible = ref([]); // 存储每个视频项是否可见
const loadedVideoCount = ref(0); // 已加载的视频数量
const videoLoadErrors = ref([]); // 存储视频加载错误状态

// 创建Intersection Observer
let observer = null;

// 初始化Intersection Observer
const initObserver = () => {
  observer = new IntersectionObserver((entries) => {
    entries.forEach(entry => {
      const index = parseInt(entry.target.dataset.index);
      if (entry.isIntersecting) {
        // 元素进入视口
        if (!isVisible.value[index]) {
          isVisible.value[index] = true;
          loadedVideoCount.value++;
          console.log(`当前视口加载了 ${loadedVideoCount.value} 个视频`);
        }
      }
    });
  }, {
    root: null, // 使用视口作为根
    rootMargin: '100px', // 提前100px开始加载，给用户更好的体验
    threshold: 0.1 // 10%可见时触发
  });
};

// 观察所有视频项
const observeVideoItems = () => {
  if (!observer) return;

  // 清除之前的观察
  videoItems.value.forEach(item => {
    if (item) observer.unobserve(item);
  });

  // 观察新的视频项
  nextTick(() => {
    videoItems.value.forEach((item, index) => {
      if (item) {
        item.dataset.index = index;
        observer.observe(item);
      }
    });

    // 确保第一个视频立即加载
    if (videoItems.value.length > 0 && videoItems.value[0]) {
      isVisible.value[0] = true;
      loadedVideoCount.value = 1;
      console.log(`第一个视频已预加载，当前视口加载了 ${loadedVideoCount.value} 个视频`);
    }
  });
};

// 处理视频加载错误
const handleVideoLoadError = (index) => {
  console.error(`视频 ${index} 加载失败`);
  videoLoadErrors.value[index] = true;
};

const getFollowVideo = async () => {
  const res = await getFollowVideoAPI(userId);
  res.data.forEach(item => {
    item.Video.userAvatar = 'http://43.138.15.137:3000' + item.Video.userAvatar;
  });

  followVideoData.value = res.data;

  // 初始化可见性数组
  isVisible.value = new Array(followVideoData.value.length).fill(false);
  // 初始化视频加载错误数组
  videoLoadErrors.value = new Array(followVideoData.value.length).fill(false);

  // 等待DOM更新后设置观察者
  nextTick(() => {
    if (!observer) {
      initObserver();
    }
    observeVideoItems();
  });
};

// 监听followVideoData变化，重新设置观察者
watch(followVideoData, () => {
  if (followVideoData.value.length > 0) {
    nextTick(() => {
      observeVideoItems();
    });
  }
});

onMounted(() => {
  getFollowVideo();
});

// 关注/视频点赞
import { likeVideoAPI, commentVideoAPI } from '@/api/follow';
const handleLike = async (videoId) => {
  // 1. 找到当前视频项
  const videoItem = followVideoData.value.find(item => item.Video.videoId === videoId);
  if (!videoItem) return;
  // 2. 调用点赞接口（后端会自动切换点赞/取消点赞状态）
  const res = await likeVideoAPI(userId, videoId);
  // 3. 根据接口返回更新点赞状态
  if (res.data === '喜欢成功') {
    // 点赞成功，增加点赞数
    videoItem.WSLCNum.likeNum++;
  } else if (res.data === '取消喜欢成功') {
    // 取消点赞成功，减少点赞数
    videoItem.WSLCNum.likeNum--;
  }
}

// 导入视频评论组件
import { defineAsyncComponent } from 'vue';
const Commentcomponent = defineAsyncComponent(() => import('@/views/home/Commentcomponent/index.vue'))
const currentVideoId = ref(null) // 新增：记录当前正在评论的视频ID

// 显示和隐藏评论弹窗
const isShowComment = ref(false);
// 评论列表
const commentList = ref([]);
// 处理新评论
const handleNewComment = (newComment) => {
  newComment.Comment.createdAt = newComment.Comment.createdAt
  // 添加到最前面
  commentList.value.unshift(newComment)
  console.log('更新后的评论列表:', commentList.value)
}
// 打开评论弹窗
const handleComment = async (videoId, index) => {
  if (!videoId || index === undefined) return
  currentVideoId.value = videoId

  try {
    const res = await commentVideoAPI(videoId)
    if (res.code === 200) {
      // 只保留原始数据，不格式化时间
      commentList.value = res.data.map(item => ({
        ...item,
        Comment: {
          ...item.Comment,
          createdAt: item.Comment.createdAt // 原始时间戳（毫秒）
        }
      }))
      isShowComment.value = true
    }
  } catch (error) {
    console.error('获取评论失败:', error)
  }
}

// 组件卸载时清理观察者
import { onBeforeUnmount } from 'vue';
import router from '@/router';
onBeforeUnmount(() => {
  if (observer) {
    observer.disconnect();
  }
});
// 跳转用户详情页
const handleUserClick = (friendId) => router.push({
  name: 'UserDetails',
  params: { friendId },
  query: { from: 'follow' } // 添加来源标识
})


</script>

<style lang="scss" scoped>
.follow {
  background-color: #161622;
  min-height: 100vh;
  /* 最小高度为视口高度，确保背景色撑满 */
  padding-bottom: 48px;
  box-sizing: border-box;
  /* 包含padding在高度计算内 */

  .no_data {
    font-size: 14px;
    color: #ccc;
    text-align: center;
    padding: 30px 0;
  }

  .follow_item {
    display: flex;
    flex-direction: column;
    gap: 10px;
    border-bottom: 1px solid #252425;
    padding: 5px;

    .follow_item_top {
      display: flex;
      align-items: center;
      gap: 5px;

      .follow_item_top__avatar {
        width: 30px;
        height: 30px;
        border-radius: 50%;
      }

      .follow_item_top__username {
        font-size: 14px;
        color: #fff;
      }
    }

    .follow_item_desc {
      font-size: 14px;
      color: #fff;
    }

    .follow_item_video {
      width: 250px;
      height: 350px;
      position: relative;

      .video_placeholder {
        width: 100%;
        height: 100%;
        background-color: #2a2a3e;
        display: flex;
        align-items: center;
        justify-content: center;
        border-radius: 8px;

        .video_placeholder__loading {
          display: flex;
          flex-direction: column;
          align-items: center;
          gap: 10px;
          color: #aaa;

          .loading_spinner {
            width: 30px;
            height: 30px;
            border: 2px solid rgba(255, 255, 255, 0.3);
            border-top: 2px solid #fff;
            border-radius: 50%;
            animation: spin 1s linear infinite;
          }

          span {
            font-size: 14px;
          }
        }
      }

      @keyframes spin {
        0% {
          transform: rotate(0deg);
        }

        100% {
          transform: rotate(360deg);
        }
      }
    }

    .follow_item_bar {
      display: flex;
      gap: 10px;

      .follow_item_bar_item {
        display: flex;
        align-items: center;
        gap: 5px;

        font-size: 14px;
        color: #fff;
      }
    }

    .follow_item_time {
      font-size: 12px;
      color: #fff;
    }
  }
}
</style>
